import React, { useState } from 'react'
import api from '../../api/axios'
import { Popup, Button, Form, Input, } from 'antd-mobile'
import { data, useNavigate } from 'react-router-dom'
function Login() {
  const Navigate = useNavigate()
  const [yzm,setYzm] = useState(0)
  const [time,setTime] = useState('')
  const onFinish = async (value) => {
    const res = await api.post('/api/login', {
      username: value.username,
      password: value.password
    })
    const {code,data} = res.data
    console.log(res)
    if(code==200){
      localStorage.setItem('token',data.token)
      localStorage.setItem('avatar',data.userInfo.avatar)
      alert('登录成功,即将到首页')
      Navigate('/')
    }
  }
  const dain=async()=>{
   const res1 = await api.get('/api/login/code',{
    params:{
      tel
    }
   })
   const {data} =res1.data
   console.log(res1)
   setYzm(data)
   setTime(5)

   let timer = setInterval(()=>{
     setTime((time)=>{
      if(time==0){
        clearInterval(timer)
        return 0
      }
      return time-1
     })
   },1000)
  }

  return (
    <div>
      <Form
        onFinish={onFinish}
        layout='horizontal'
        footer={
          <Button block type='submit' color='primary' size='large'>
            登录
          </Button>
        }
      >
        <Form.Item
          name='tel'
          label='用户名'
          rules={[{ required: true, message: '用户名不能为空' }]}
        >
          <Input placeholder='请输入用户名' />
        </Form.Item>
        <Form.Item
          name='telCode'
          label='密码'
          
          rules={[{ required: true, message: '密码不能为空' }]}
        >
          <Input placeholder='请输入密码' value={yzm} />
          <Button onClick={()=>dain()} disabled={time>0}>{time>0?`${time}后发送`:'重新获取'}</Button>
        </Form.Item>
      </Form>
    </div>
  )
}

export default Login
